<script lang="ts">
import { Message, Money, Tickets, Star, User, SwitchButton, CaretBottom, Upload, Notebook } from '@element-plus/icons-vue'

import { ComponentSize, ElMessageBox, FormInstance, FormRules } from 'element-plus';

import { ref, reactive, onMounted } from 'vue'


import { useUserInfoStore } from '@/stores/userInfo.js'

import { userInfoGetService, userAvatarUpdateService, updatePassword, userInfoUpdateService } from '@/api/user.js'

import { ElMessage } from 'element-plus'
import { useTokenStore } from '@/stores/token';
import router from '@/router';
import request from '@/utils/request.js'

//获取个人信息
const getUserInfo = async () => {
    try {
        let result = await userInfoGetService();
        if (result.data) {
            userInfoStore.info = result.data;
            // 只更新需要的表单数据
            ruleForm.name = result.data.username || '';
            ruleForm.email = result.data.email || '';
            ruleForm.career = result.data.career || '';
            // 不设置密码字段
        }
    } catch (error) {
        console.error('获取用户信息失败:', error);
        ElMessage.error('获取用户信息失败');
    }
}

// 在组件挂载时获取用户信息
onMounted(() => {
    getUserInfo();
})

const updateAvatar = async () => {
    let result = await userAvatarUpdateService(imgUrl.value)
    ElMessage.success(result.data ? result.data : '修改成功')
    //更新pinia中的数据
    userInfoStore.info.userPic = imgUrl.value
}
const userInfoStore = useUserInfoStore()

const uploadRef = ref()

const imgUrl = ref(userInfoStore.info?.userPic || '')

//图片上传成功的回调
const uploadSuccess = (result) => {
    //回显片
    imgUrl.value = result.data
}

//用户头像地址
// const imgUrl= avatar

interface RuleForm {
    name: string
    career: string
    date1: string
    date2: string
    location: string
    password: string
    newPassword: string
    email: string,
    avatar: string
}

const formSize = ref<ComponentSize>('default')
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
    name: userInfoStore.info.username || '',
    career: '',
    location: '',
    email: userInfoStore.info.email || '',
    date1: '',
    date2: '',
    avatar: '',
    old_pwd: userInfoStore.info.password || '',
    new_pwd: '',
    re_pwd: ''
})

const rules = reactive({
    name: [
        { required: true, message: '请输昵称', trigger: 'blur' },
        { min: 3, max: 16, message: '长度至少3到16个字符', trigger: 'blur' },
    ],
    career: [
        { required: true, message: '请输入您的职业', trigger: 'blur' },
    ],
    date1: [
        {
            type: 'date',
            required: true,
            message: '请选择开始时间',
            trigger: 'change',
        },
    ],
    date2: [
        {
            type: 'date',
            required: true,
            message: '请择结束时间',
            trigger: 'change',
        },
    ],
    location: [
        { required: true, message: '请选择工作地点', trigger: 'change' },
        { type: 'array', required: true, message: '请选择工作地点', trigger: 'change' }
    ],
    email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        {
            validator: (rules, value, callback) => {
                const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; // 正则表达式
                if (!value) {
                    callback(new Error('请输入电子邮箱'));
                } else if (!emailPattern.test(value)) {
                    callback(new Error('请输入正确的电子邮箱'));
                } else {
                    callback();
                }
            },
            trigger: 'blur'
        },
    ],
    old_pwd: [
        { required: true, message: '请输入原密码', trigger: 'blur' },
        { min: 5, max: 16, message: '密码长度在 5 到 16 个字符', trigger: 'blur' }
    ],
    new_pwd: [
        { required: true, message: '请输入新密码', trigger: 'blur' },
        { min: 5, max: 16, message: '密码长度在 5 到 16 个字符', trigger: 'blur' }
    ],
    re_pwd: [
        { required: true, message: '请再输入新密码', trigger: 'blur' },
        { min: 5, max: 16, message: '密码长度在 5 到 16 个字符', trigger: 'blur' },
        {
            validator: (rule, value, callback) => {
                if (value !== ruleForm.new_pwd) {
                    callback(new Error('两次输入的密码不一致'))
                } else {
                    callback()
                }
            },
            trigger: 'blur'
        }
    ]
})

const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            console.log('submit!')
        } else {
            console.log('error submit!', fields)
        }
    })
}

const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}

const options = Array.from({ length: 10000 }).map((_, idx) => ({
    value: `${idx + 1}`,
    label: `${idx + 1}`,
}))

const currentPage4 = ref(1)
const pageSize4 = ref(5)
const size = ref<ComponentSize>('default')

const handleSizeChange = (val: number) => {
    console.log(`${val} items per page`)
}
const handleCurrentChange = (val: number) => {
    console.log(`current page: ${val}`)
}

const handleOpen = (key: string, keyPath: string[]) => {
    console.log(key, keyPath)
}
const handleClose = (key: string, keyPath: string[]) => {
    console.log(key, keyPath)
}

const handleCommand = (command) => {
    if (command === 'logout') {
        //退出登录
        ElMessageBox.confirm(
            '你确认退出登录吗？',
            '温馨提示',
            {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
            }
        )
            .then(async () => {
                try {
                    // 清空pinia中的token和个人信息
                    const tokenStore = useTokenStore();
                    tokenStore.removeToken();

                    // 跳转到登录页
                    router.push('/login');

                    // 更新 localStorage
                    localStorage.setItem('isLoggedIn', 'false');
                } catch (error) {
                    console.error("发生错：", error);
                    // 可以选择是否在这里显示错误消息或其他处理
                }
            })
            .catch(() => {
                // 用户点击了取消
                ElMessage({
                    type: 'info',
                    message: '取消退出',
                });
            });
    }
}



export default {
    components: {
        Message,
        Money,
        Tickets,
        Star,
        User,
        SwitchButton,
        CaretBottom,
        Upload,
        Notebook
    },
    data() {
        return {
            handleOpen: '',
            handleClose: '',
            activeIndex: '2',
            searchQuery: '',
            isDark: false,
            currentPage4,
            pageSize4,
            size,
            userInfoStore,
            handleSizeChange,
            handleCurrentChange,
            handleCommand,
            User,
            SwitchButton,
            userAvatar: 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif',
            handleSelect: '',
            recharge: '',
            withdraw: '',
            ruleForm,
            rules,
            formSize,
            updateAvatar,
            imgUrl,
            updatePassword,
        }
    },
    methods: {
        setDefaultLogo(event) {
            event.target.src = 'images/default-logo.jpg';
        },
        search() {
            // 处理搜索逻辑
            console.log(`搜索内容: ${this.searchQuery}`);
        },
        filter(option) {
            // 处理过滤逻辑
            console.log(`过滤选项: ${option}`);
        },
        navigateTologin(page) {
            this.$router.push(`/${page}`); // 跳转到登录页面
        },
        navigateToregister(page) {
            this.$router.push(`/${page}`); // 跳转到登录页面
        },
        navigateTo(link) {
            window.location.href = link;
        },
        async handleAvatarUpload(file) {
            try {
                // 创建 FormData 对象来处理文件上传
                const formData = new FormData();
                const rawFile = file.file || file;
                formData.append('file', rawFile);

                // 修改为正确的文件上传路径
                console.log('开始上传文件...');
                const uploadResponse = await request.post('/upload', formData, {  // 修改这里的上传路径
                    headers: {
                        'Content-Type': 'multipart/form-data',
                        'Authorization': useTokenStore().token
                    }
                });

                console.log('上传响应:', uploadResponse);

                // 检查上传响应
                if (!uploadResponse.data) {
                    ElMessage.error('文件上传失败: 没有响应数据');
                    return;
                }

                // 获取到文件URL后，调用更新头像接口
                const avatarUrl = uploadResponse.data.data;
                console.log('获取到的头像URL:', avatarUrl);

                if (!avatarUrl) {
                    ElMessage.error('文件上传失败: 未获取到URL');
                    return;
                }

                // 使用 userAvatarUpdateService 更新头像
                console.log('开始更新头...');
                const response = await userAvatarUpdateService(avatarUrl);
                console.log('更新头像响应:', response);

                if (response.data.code === 0) {
                    // 更新本地显示
                    this.imgUrl = avatarUrl;
                    // 更新用户息中的头像
                    this.userInfoStore.info.userPic = avatarUrl;
                    ElMessage.success('头像更新成功');
                } else {
                    ElMessage.error(response.data.message || '头像更新失败');
                }
            } catch (error) {
                console.error('头像更新失败:', error);
                console.error('错误详情:', {
                    message: error.message,
                    response: error.response,
                    request: error.request
                });

                if (error.response?.data?.message) {
                    ElMessage.error(`头像更新失败: ${error.response.data.message}`);
                } else {
                    ElMessage.error('头像更新失败，请试');
                }
            }
        },
        // 修改密码更新的处理方法
        async handleUpdatePassword() {
            try {
                const response = await updatePassword(this.ruleForm);
                console.log('密码修改响应:', response);

                if (response && response.data) {
                    // 先显示成功消息
                    ElMessage.success('密码修改成功，请重新登录');

                    // 延迟执行清理和跳转操作
                    setTimeout(() => {
                        // 清空密码表单
                        this.ruleForm.old_pwd = '';
                        this.ruleForm.new_pwd = '';
                        this.ruleForm.re_pwd = '';

                        // 清除 token
                        const tokenStore = useTokenStore();
                        tokenStore.removeToken();

                        // 清除用户信息
                        this.userInfoStore.info = {
                            username: '',
                            userPic: '',
                            id: '',
                            email: ''
                        };

                        // 清除本地存储的密码相关信息
                        localStorage.removeItem('password');
                        localStorage.removeItem('userPassword');
                        sessionStorage.removeItem('password');
                        sessionStorage.removeItem('userPassword');

                        // 跳转到登录页
                        this.$router.push('/login');
                    }, 1500);
                    return;
                }

                ElMessage.error(response?.data?.message || '密码修改失败');
                
            } catch (error) {
                console.error('密码修改失败:', error);
                ElMessage.error(error.response?.data?.message || '密码修改失败，请重试');
            }
        },
        // 在 methods 中添加保存职业的方法
        async handleUpdateCareer() {
            try {
                if (!this.ruleForm.career) {
                    ElMessage.error('职业不能为空');
                    return;
                }

                // 构造更新对象，包含所有必需字段
                const updateData = {
                    id: this.userInfoStore.info.id,
                    username: this.userInfoStore.info.username,
                    email: this.userInfoStore.info.email,
                    career: this.ruleForm.career
                };

                console.log('发送更新请求:', updateData);
                const response = await userInfoUpdateService(updateData);
                console.log('更新响应:', response);

                // 修改判断逻辑
                if (response.data.code === 0) {
                    // 更新本地显示
                    this.userInfoStore.info.career = this.ruleForm.career;
                    ElMessage.success('职业信息保存成功');
                    // 不再调用 getUserInfo，直接使用更新后的值
                    console.log('更新后的用户信息:', this.userInfoStore.info);
                } else {
                    console.error('更新失败:', response);
                    ElMessage.error(response.data?.message || '保存失败');
                }
            } catch (error) {
                console.error('保存失败:', error);
                console.error('错误详情:', {
                    message: error.message,
                    response: error.response,
                    data: error.response?.data
                });
                ElMessage.error(error.response?.data?.message || '保存失败，请重试');
            }
        },

        beforeAvatarUpload(file) {
            // 文件类型检查
            const isImage = ['image/jpeg', 'image/png', 'image/gif'].includes(file.type);
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isImage) {
                ElMessage.error('头像能是 JPG/PNG/GIF 格式!');
                return false;
            }
            if (!isLt2M) {
                ElMessage.error('头像大小不能超过 2MB!');
                return false;
            }
            return true;
        },

        async handleUpdateUsername() {
            try {
                if (!this.ruleForm.name) {
                    ElMessage.error('昵称不能为空');
                    return;
                }

                // 构造更新对象
                const updateData = {
                    id: this.userInfoStore.info.id,
                    username: this.ruleForm.name,
                    email: this.ruleForm.email
                };

                console.log('发送更新请求:', updateData);
                const response = await userInfoUpdateService(updateData);
                console.log('更新响应:', response);

                if (response.data) {
                    // 更新本地显示
                    this.userInfoStore.info.username = this.ruleForm.name;
                    ElMessage.success('昵称修改成功');
                    // 重新获取用户信息
                    await getUserInfo();
                    
                    // 延迟执行清理和跳转操作
                    setTimeout(() => {
                        // 清空表单
                        this.ruleForm.username = '';

                        // 清除 token
                        const tokenStore = useTokenStore();
                        tokenStore.removeToken();

                        // 清除用户信息
                        this.userInfoStore.info = {
                            username: '',
                            userPic: '',
                            id: '',
                            email: ''
                        };

                        // 清除所有密码相关的缓存
                        localStorage.removeItem('password');
                        localStorage.removeItem('userPassword');
                        sessionStorage.removeItem('password');
                        sessionStorage.removeItem('userPassword');

                        // 跳转到登录页
                        this.$router.push('/login');
                    }, 1500);
                    return;
                }

                console.error('更新失败:', response);
                ElMessage.error('昵称修改失败');
            } catch (error) {
                console.error('昵称修改失败:', error);
                ElMessage.error(error.response?.data?.message || '昵称修改失败，请重试');
            }
        },

        // 添加修改邮箱的方法
        async handleUpdateEmail() {
            try {
                if (!this.ruleForm.email) {
                    ElMessage.error('邮箱不能为空');
                    return;
                }

                // 构造更新对象
                const updateData = {
                    id: this.userInfoStore.info.id,
                    username: this.userInfoStore.info.username,
                    email: this.ruleForm.email,
                    career: this.ruleForm.career
                };

                console.log('发送更新请求:', updateData);  // 添加日志
                const response = await userInfoUpdateService(updateData);
                console.log('更新响应:', response);  // 添加日志

                // 修改判断逻辑
                if (response.data) {  // 成功
                    // 更新本地显示
                    this.userInfoStore.info.email = this.ruleForm.email;
                    ElMessage.success('邮箱绑定成功');
                    // 重新获取用户信息
                    await getUserInfo();
                } else {
                    console.error('更新失败:', response);  // 添加错误日志
                    ElMessage.error('邮箱绑定失败');
                }
            } catch (error) {
                console.error('邮箱绑定失败:', error);
                console.error('错误详情:', {
                    message: error.message,
                    response: error.response,
                    data: error.response?.data
                });
                ElMessage.error(error.response?.data?.message || '邮箱绑定失败，请重试');
            }
        }
    }
}

</script>

<template>
    <el-menu :default-active="activeIndex" class="el-menu-demo" mode="horizontal" :ellipsis="false"
        @select="handleSelect" style="height:75px;box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
        <el-menu-item index="0">
            <img style="width: 100px;height: 70px;margin-left: 53px;margin-right: 10px;" src="@/assets/logo.jpg"
                alt="CodeCash" />
        </el-menu-item>
        <el-search-item index="1" style="transform: translate(-100%,15px);">
            <el-input v-model="searchQuery" style="width: 300px;height:40px;" placeholder="搜索您感兴趣的内容" clearable />
            <el-button type="search" style="height: 40px;background-color:#007bff;color:white;">搜索</el-button>
        </el-search-item>
        <el-router-menu index="2" style="transform: translateX(-2%);">
            <el-link href="/" style="color: black; font-size: 18px;padding: 20px;">首页</el-link>
            <el-link href="/programmer" style="color: black; font-size: 18px;padding: 20px;">程序员</el-link>
            <el-link href="/task" style="color: black; font-size: 18px;padding: 20px;">任务大厅</el-link>
            <el-link href="/community" style="color: black; font-size: 18px;padding: 20px;">社区</el-link>
            <el-link href="/user/call" style="color: black; font-size: 18px;padding: 20px;">联系我们</el-link>
        </el-router-menu>
        <el-buttons-item index="3" style="transform: translateY(25%);margin-right: 20px;">
            <el-dropdown placement="bottom-end">
                <el-avatar :src="userAvatar" size="medium" />
                <el-icon>
                    <CaretBottom />
                </el-icon>
                <template #dropdown>
                    <el-dropdown-menu>
                        <el-dropdown-item command="userInfo" :icon="User"
                            @click="navigateTo('/userInfo')">个人中心</el-dropdown-item>
                        <el-dropdown-item command="logout" :icon="SwitchButton"
                            @click="handleCommand('logout')">退出登录</el-dropdown-item>
                    </el-dropdown-menu>
                </template>
            </el-dropdown>
        </el-buttons-item>
    </el-menu>
    <el-aside width="200px" height="700vh" style="margin-left: 300px;">
        <div
            style="margin-left: -40px;margin-top: 20px;align-items: center;justify-content: center;display: flex;flex-direction: column;">
            <el-avatar :src="userInfoStore.info?.userPic || userAvatar" />
            <h5 class="mb-2">{{ userInfoStore.info?.username }}</h5>
            <el-button color="#2994F2">已签约</el-button>
        </div>
        <el-divider />
        <el-menu default-active="2" class="el-menu-vertical-demo" @open="handleOpen" @close="handleClose">
            <el-menu-item index="1" @click="navigateTo('/userInfo')">
                <el-icon>
                    <Money />
                </el-icon>
                <span>账户金额</span>
            </el-menu-item>
            <el-menu-item index="2" @click="navigateTo('/userInfo/message')">
                <el-icon>
                    <Message />
                </el-icon>
                <span>账户信息</span>
            </el-menu-item>
            <el-menu-item index="3" @click="navigateTo('/userInfo/task')">
                <el-icon>
                    <Notebook />
                </el-icon>
                <span>我的任务</span>
            </el-menu-item>
            <el-menu-item index="4" @click="navigateTo('/userInfo/favorite')">
                <el-icon>
                    <Star />
                </el-icon>
                <span>我的收藏</span>
            </el-menu-item>
            <el-menu-item index="5" @click="navigateTo('/userInfo/list')">
                <el-icon>
                    <Tickets />
                </el-icon>
                <span>订单列表</span>
            </el-menu-item>
        </el-menu>
    </el-aside>
    <el-container style="margin-left: 100px;">
        <el-header style="margin-left: 450px;margin-top: -400px;">
            <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules" label-width="auto"
                class="demo-ruleForm" :size="formSize" status-icon>
                <el-form-item label="头像" prop="avatar">
                    <div class="avatar-container">
                        <el-upload class="avatar-uploader" :show-file-list="false" :http-request="handleAvatarUpload"
                            :before-upload="beforeAvatarUpload">
                            <el-button type="primary" size="small">
                                <el-icon>
                                    <Upload />
                                </el-icon>
                                更换头像
                            </el-button>
                        </el-upload>
                    </div>
                </el-form-item>
                <el-form-item label="昵称" prop="name">
                    <div style="display: flex; gap: 10px; align-items: center;">
                        <el-input v-model="ruleForm.name" />
                        <el-button type="primary" @click="handleUpdateUsername">保存</el-button>
                    </div>
                </el-form-item>
                <el-form-item label="职业" prop="career">
                    <div style="display: flex; gap: 10px; align-items: center;">
                        <el-input v-model="ruleForm.career" />
                        <el-button type="primary" @click="handleUpdateCareer">保存</el-button>
                    </div>
                </el-form-item>
                <el-form-item label="可工作时间" required>
                    <div class="work-time-container">
                        <div class="time-row">
                            <span class="time-label">工作日：</span>
                            <el-time-picker v-model="ruleForm.date1" placeholder="开始时间" style="width: 150px;" />
                            <span class="time-separator">至</span>
                            <el-time-picker v-model="ruleForm.date2" placeholder="结束时间" style="width: 150px;" />
                        </div>
                        <div class="time-row">
                            <span class="time-label">周末：</span>
                            <el-time-picker v-model="ruleForm.date1" placeholder="开始时间" style="width: 150px;" />
                            <span class="time-separator">至</span>
                            <el-time-picker v-model="ruleForm.date2" placeholder="结束时间" style="width: 150px;" />
                        </div>
                    </div>
                </el-form-item>
                <el-form-item label="所在地区" prop="location">
                    <el-input v-model="ruleForm.location" />
                </el-form-item>
                <el-divider />
                <el-form-item label="原密码" prop="old_pwd">
                    <el-input v-model="ruleForm.old_pwd" type="password" show-password placeholder="请输入原密码" />
                </el-form-item>
                <el-form-item label="新密码" prop="new_pwd">
                    <el-input v-model="ruleForm.new_pwd" type="password" show-password placeholder="请输入新密码" />
                </el-form-item>
                <el-form-item label="确认密码" prop="re_pwd">
                    <el-input v-model="ruleForm.re_pwd" type="password" show-password placeholder="请再次输入新密码" />
                </el-form-item>
                <el-form-item>
                    <div style="display: flex; justify-content: center; width: 100%;">
                        <el-button type="primary" @click="handleUpdatePassword">确认修改</el-button>
                    </div>
                </el-form-item>
                <el-divider />
                <el-form-item label="实名认证" prop="realName">
                    <el-button color="#2994F2">去认证</el-button>
                    <!-- 看是否实现不实现添加弹窗信息 -->
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <div style="display: flex; gap: 10px; align-items: center;">
                        <el-input v-model="ruleForm.email" style="width: 300px;" />
                        <el-button type="primary" @click="handleUpdateEmail">立即绑定</el-button>
                    </div>
                </el-form-item>
            </el-form>
        </el-header>
    </el-container>
    <el-footer>
        <div class="footer">
            <div>
                <a href="#">动态公告</a> |
                <a href="#">帮助</a> |
                <a href="#">关于我们</a> |
                <a href="#">合作伙伴</a> |
                <a href="#">意见反馈</a> |
                <text style="color: rgb(78, 77, 77);">@“码上有钱”程序员接单平台</text>
            </div>
            <div class="credits">
                粤ICP备20220901号-4 | 粤公网安备33011002011599号
            </div>
        </div>
    </el-footer>
</template>

<style scoped>
.el-menu--horizontal>.el-menu-item:nth-child(1) {
    margin-right: auto;
}

.footer {
    margin-top: 350px;
    padding: 10px 0;
    border-top: 1px solid #ddd;
    text-align: center;
}

.footer a {
    text-decoration: none;
    color: rgb(78, 77, 77);
    background: transparent;
    border: none;
    cursor: pointer;
}

.footer .credits {
    margin-top: 5px;
    font-size: 12px;
    color: gray;
}

/* 头像上传相关样式 */
.avatar-container {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
}

.avatar-uploader {
    text-align: left;
}

.el-upload__tip {
    font-size: 12px;
    color: #909399;
    margin-top: 8px;
}

/* 修改可工作时间相关样式 */
.work-time-container {
    display: flex;
    flex-direction: column;
    gap: 20px;
}

.time-row {
    display: flex;
    align-items: center;
    gap: 15px;
}

.time-label {
    font-size: 14px;
    color: #606266;
    width: 80px;
    margin-right: 10px;
}

.time-separator {
    color: #909399;
    margin: 0 15px;
    font-size: 14px;
}
</style>